class QueryPropertyOrg extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            nodes: [],
            staffNodes : [],
            leaderStaffNodes : [],
            orgs: [],
            roles: [],
            managerDevCount:0,
            showDevs : "",
            staffForm :{},
            orgForm : {},
        };

        this.devBindingLimit = 5;
        /* header中的功能提示语 */
        this.pageTips = "1. 请创建您的物业组织架构,方便对人员有一个清晰的管理<br>" +
                        "2. 请在组织中创建人员, 选择合适的职位<br>" +
                        "3. 请建立自己的APP角色，分配手机端的权限<br>" +
                        "4. 分配角色给物业员工";

        this.appAuthTips = "1. 开启APP权限会自动创建手机APP端账号,默认密码123456,也可以不开启。<br>"+
                           "2. 创建不同的权限角色对应着APP物管用户的不同操作权限";
    }

    updateOrgList(commCode) {
        postJson("/property/org/getList.x", {commCode:commCode}, (data) => {
            let orgsData = data.data;
            if (orgsData.length == 0)
                layui.layer.msg("您还没有构建组织架构,请添加新增部门选项卡");

            postJson("/property/staff/getByComm.x", {commCode:commCode}, (data) => {
                let staffDatas = data.data;
                for (let i = 0; i < staffDatas.length; i++) {
                    staffDatas[i].parentId = staffDatas[i].orgId;
                    staffDatas[i].iconclass = "fa fa-user";
                    staffDatas[i].orgName = staffDatas[i].staffName;
                    staffDatas[i].id = staffDatas[i].orgId+"-"+staffDatas[i].staffId;
                }

                staffDatas.push(...orgsData);
                let staffNodes = this.refs.staffTreeModal.getNodes(staffDatas,null,'parentId','id','orgName');
                let nodes = this.refs.orgModal.getNodes(orgsData, null, 'parentId', 'id', 'orgName');
                let orgs = [];
                reorderParents(staffDatas, null, orgs, 'parentId', 'id');
                this.refs.orgTable.removeTreeTable();
                this.setState({
                    nodes: nodes,
                    staffTreeOrgNodes:nodes,
                    orgs: orgs,
                    staffNodes:staffNodes,
                    leaderStaffNodes:staffNodes
                });
            })

        })
    }

    updatePerms() {
        if (this.state.perms.length == 0) {
            postJson("/property/app/modules/")
        }
    }

    onChangeComm(commCode) {
        this.setState({orgs: [],currentComm:commCode});
        this.updateOrgList(commCode);
        this.headQuarters = !commCode;
        if(!this.headQuarters) {
            postJson("/man/getManagerDevCount.x", {commCode:commCode}, (devData) => {
                this.setState({managerDevCount: devData.data});
            });
        }
    }

    setLeaderReadOnly(state){
        this.refs.leaderInput.refs.input.setState({readonly:state});
        this.refs.phoneNum.setState({readonly:state});
    }

    createOrg() {
        let leader = this.refs.leaderModal.value;
        let orgForm = this.state.orgForm;
        orgForm.commCode = this.refs.commSelect.commCode;
        if(leader)
            orgForm.staffId = leader.staffId;

        let staffExist = this.getStaffByMob(orgForm.phoneNum);
        if((!leader || !leader.staffId) && staffExist.length > 0){
            for(let i=0; i<staffExist.length; i++) {
                if (staffExist[i].staffName != orgForm.staffName) {
                    layui.layer.alert("手机号 " + staffExist[i].phoneNum + " 已被用户[" + staffExist[i].staffName + "]使用，请重新修改信息");
                    return;
                } else {
                    layui.layer.alert("用户[" + staffExist[i].staffName + "]已存在，请从列表中选择");
                    return;
                }
            }
        }

        postJson("/property/org/update.x", orgForm, () => {
            layui.layer.msg("创建成功");
            this.updateOrgList(orgForm.commCode);
            this.setState({orgs: [],orgForm:emptyObj(this.state.orgForm)});
        })
    }

    removeOrgById(id) {
        let orgCopy = Object.create(this.state.orgs);
        for (let i = 0; i < orgCopy.length; i++) {
            if (id == orgCopy[i].id) {
                orgCopy.splice(i, 1);
            }
        }
        this.state.nodes = this.refs.orgModal.getNodes(orgCopy, null, 'parentId', 'id', 'orgName');
    }

    delete(org) {
        layui.layer.confirm("确定要删除" + org.orgName + "以及所属子部门和所有员工信息么?", (index) => {
            postJson("/property/org/delete.x", {id: org.id}, () => {
                this.refs.orgTable.removeTreeTable();
                this.removeOrgById(org.id);
                this.updateOrgList(this.refs.commSelect.commCode);
                layui.layer.msg("删除成功");
            });
            layui.layer.close(index);
        });
    }

    tabOnChange(index) {
        if (index == 0 && this.created) {
            this.created = false;
            location.reload();
        }else if( index == 0 ){
            this.setState({orgForm : emptyObj(this.state.orgForm)});
        }
        if(index == 1){
            this.setLeaderReadOnly(false);
        }
    }

    assign(org) {
        let orgForm = emptyObj(this.state.orgForm);
        orgForm.parentOrg = org.orgName;
        orgForm.parentId = org.id;
        this.setState({orgForm:orgForm});
        this.refs.tab.changeTab('1');
    }

    getOrg(id) {
        for (let i = 0; i < this.state.orgs.length; i++) {
            if (this.state.orgs[i].id == id) {
                return this.state.orgs[i];
            }
        }
    }

    getStaffByMob(phoneNum) {
        let exist = [];
        for (let i = 0; i < this.state.orgs.length; i++) {
            if (this.state.orgs[i].phoneNum == phoneNum) {
                exist.push(this.state.orgs[i]);
            }
        }
        return exist;
    }

    checkDevBindingLimit(phoneNum){
        let count = 0;

        for(let i=0; i< this.state.orgs.length; i++){
            if(this.state.orgs[i].devBinding) {
                if(this.state.orgs[i].phoneNum === phoneNum)
                    return false;
                else
                    count++;
            }
        }

        return count >= this.devBindingLimit;
    }

    modify(org) {
        let parent = this.getOrg(org.parentId);
        postJson("/property/staff/getByOrg.x", {orgId: org.id,staffType : 3}, (data) => {
            let orgForm = {};
            orgForm.id = org.id;
            orgForm.orgName = org.orgName;
            orgForm.parentOrg = parent?parent.orgName:'';
            orgForm.parentId = parent?parent.id:'';
            if (data.data.length > 0) {
                orgForm.staffName = data.data[0].staffName ? data.data[0].staffName : '';
                orgForm.phoneNum = data.data[0].phoneNum ? data.data[0].phoneNum : '';
                orgForm.email = data.data[0].email ? data.data[0].email : '';
            }

            this.setState({orgForm:orgForm});
            this.refs.tab.changeTab('1');
            this.setLeaderReadOnly(true);
        })

    }

    updateStaffFormWithId(staffId,orgId,staffOrgId,callback){
        let needDevBindingForStaff = !!this.refs.commSelect.commCode;
        postJson("/property/staff/getStaffInfo.x",{id:staffId,devBinding:needDevBindingForStaff},(staffData)=>{
            let staffInfo = staffData.data.staff;
            let devBinding = staffData.data.devBinding;
            let org = this.getOrg(orgId);
            let staffForm = {};
            staffForm.staffName = staffInfo.staffName;
            staffForm.staffType = staffInfo.staffType;
            staffForm.phoneNum = staffInfo.phoneNum;
            staffForm.email = staffInfo.email;
            if(org) {
                staffForm.orgName = org.orgName;
                staffForm.orgId = org.id;
                staffForm.commCode = org.commCode;
            }
            staffForm.staffId = staffInfo.id;
            staffForm.staffOrgId = staffOrgId;
            staffForm.role = staffInfo.role?staffInfo.role:'';

            staffForm.devBinding = devBinding;
            this.setState({staffForm:staffForm});
            if(callback)
                callback();
        })
    }

    modifyStaff(staff) {

        if(this.state.roles.length == 0){
            postJson("/property/app/role/queryAll.x", null, (data) => {
                this.setState({roles:data.data});
            })
        }

        this.updateStaffFormWithId(staff.staffId,staff.orgId,staff.staffOrgId,()=>{
            this.staffModify = true;
            this.refs.staffModal.show({title:'修改员工'});
        })

    }

    deleteStaff(staff) {
        layui.layer.confirm("确定要删除此员工么?",()=>{
            postJson("/property/staff/deleteOrgStaff.x",staff,()=>{
                layui.layer.msg("删除成功!");
                this.updateOrgList(this.refs.commSelect.commCode);
            })
        })
    }

    assignStaff(org) {
        if(this.state.roles.length == 0) {
            postJson("/property/app/role/queryAll.x", null, (data) => {
                this.setState({roles: data.data});
            })
        }

        let staffForm = emptyObj(this.state.staffForm);
        staffForm.orgName = org.orgName;
        staffForm.orgId = org.id;
        this.setState({staffForm:staffForm},()=>{
            this.staffModify = false;
            this.refs.staffModal.show();
        });

    }

    addStaff() {
        let staffForm = this.state.staffForm;
        staffForm.commCode = this.refs.commSelect.commCode;

        let staffExist = this.getStaffByMob(staffForm.phoneNum);

        if (staffExist.length > 0) {
            for(let i= 0; i < staffExist.length; i++) {
                if (staffExist[i].staffName !== staffForm.staffName) {
                    layui.layer.alert("手机号 " + staffExist[i].phoneNum + " 已被用户[" + staffExist[i].staffName + "]使用，请重新修改信息",{icon:5});
                    return;
                } else if (!staffForm.staffId) {
                    layui.layer.alert("用户[" + staffExist[i].staffName + "]已存在，请从列表中选择",{icon:5});
                    return;
                } else if (staffExist[i].orgId === staffForm.orgId && !this.staffModify) {
                    layui.layer.alert("该部门已存在此用户",{icon:5});
                    return;
                }
            }
        }

        if(this.checkDevBindingLimit(staffForm.phoneNum)){
            layui.layer.alert("非常抱歉，目前您最多只能指定"+this.devBindingLimit+"个员工绑定门禁呼叫!",{icon:5});
            return;
        }

        postJson("/property/staff/save.x",staffForm,()=>{
            layui.layer.msg("保存成功");
            this.updateOrgList(staffForm.commCode);
            this.refs.staffModal.close();

        });
    }

    getOrgName(org) {
        if (org.staffName)
            return [<i className="fa fa-user"
                       style={org.staffType == 3 ? {color: 'green'} : {}}/>, " " + org.staffName];
        else
            return org.orgName;
    }

    goToRolePage() {
        window.location = "/pages/business/property/role.html";
    }

    getManagerDevOption(){
        let optionStr = [];
        for(let i=1; i<=this.state.managerDevCount;i++){
            optionStr.push(<option value={i+''}>管理机-{i}</option>);
        }
        return optionStr;
    }

    getBtns(org) {
        if (org.staffName) {
            return (
                [
                    <Button btnType="normal" size="xs" onClick={() => this.modifyStaff(org)}>修改</Button>,
                    <Button btnType="danger" size="xs" onClick={() => this.deleteStaff(org)}>删除</Button>
                ]
            )
        } else {
            return (
                [
                    <Button btnType="normal" size="xs" onClick={() => this.modify(org)}>修改</Button>,
                    <Button btnType="danger" size="xs" onClick={() => this.delete(org)}>删除</Button>,
                    <Button btnType="primary" size="xs" onClick={() => this.assign(org)}>分配下级部门</Button>,
                    <Button size="xs" onClick={() => this.assignStaff(org)}>创建员工</Button>
                ]
            )
        }
    }

    leaderSelected(string,data){
        if(!data.staffName) {
            layui.layer.msg("请选择员工");
            return
        }

        this.refs.leaderInput.value = string;

        postJson("/property/staff/getStaffInfo.x",{id:data.staffId},(staffInfo)=>{
            let orgForm = this.state.orgForm;
            orgForm.phoneNum = staffInfo.data.staff.phoneNum;
            orgForm.email = staffInfo.data.staff.email;

            this.setState({orgForm : orgForm});
        })

    }

    staffSelect(string,data){
        if(!data.staffName) {
            layui.layer.msg("请选择员工");
            return
        }

        console.log(data);
        this.updateStaffFormWithId(data.staffId,this.state.staffForm.orgId);
    }

    staffChange(name,value){
        this.state.staffForm[name] = value;
        this.setState({staffForm:this.state.staffForm});
    }

    staffCommOnChange(commCode){
        postJson("/property/org/getList.x", {commCode:commCode}, (data) => {
            let nodes = this.refs.orgModal.getNodes(data.data, null, 'parentId', 'id', 'orgName');
            this.state.staffForm.commCode = commCode;
            this.setState({staffTreeOrgNodes:nodes});
        });
    }

    leaderCommOnChange(commCode){
        postJson("/property/org/getList.x", {commCode:commCode}, (data) => {
            let orgsData = data.data;
            postJson("/property/staff/getByComm.x", {commCode:commCode}, (data) => {
                let staffDatas = data.data;
                for (let i = 0; i < staffDatas.length; i++) {
                    staffDatas[i].parentId = staffDatas[i].orgId;
                    staffDatas[i].iconclass = "fa fa-user";
                    staffDatas[i].orgName = staffDatas[i].staffName;
                    staffDatas[i].id = staffDatas[i].orgId+"-"+staffDatas[i].staffId;
                }

                staffDatas.push(...orgsData);
                let staffNodes = this.refs.staffTreeModal.getNodes(staffDatas,null,'parentId','id','orgName');

                this.setState({leaderStaffNodes:staffNodes});
            })

        })
    }

    orgChange(name,value){
        this.state.orgForm[name] = value;
        this.setState({orgForm:this.state.orgForm});
    }

    render() {
        return (
            <Frame header="组织管理" tips={this.pageTips} headerBtns={
                [
                    <HeaderBtn onClick={()=>{
                        this.refs.orgTable.collapseAll()}}><i className="fa fa-chevron-up"></i></HeaderBtn>,
                    <HeaderBtn onClick={()=>{this.refs.orgTable.expandAll()}}><i className="fa fa-chevron-down"></i></HeaderBtn>,
                    <Form frameStyle={{display:"inline"}} style={{display:"inline",marginLeft:5}}>
                        <LayuiCommSelect size="sm" mask={['building', 'unit', 'floor', 'room']} ref="commSelect" firstValue={hasRoles("admin | secLevel")?"公司总部":''}
                                           value={this.state.currentComm} onChangeComm={(comm) => this.onChangeComm(comm)}/>
                    </Form>
                ]
            }
            >
                <Tab titles={['部门列表', '新增部门']} ids={['0', '1']} type="brief"
                     onChange={(index) => this.tabOnChange(index)} ref="tab">
                    <TabItem show="true">
                        <Table expandable="true" ref="orgTable">
                            <thead>
                            <tr>
                                <th>部门名称</th>
                                <th>联系方式 <Tips>电话图标代表该员工绑定了门禁管理机呼叫</Tips></th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            {
                                this.state.orgs.map((org) => {
                                    return (
                                        <tr data-tt-id={org.id} data-tt-parent-id={org.parentId}>
                                            <td>{this.getOrgName(org)}</td>
                                            <td>{org.phoneNum?org.phoneNum:''}&nbsp;{org.devBinding?<i className="fa fa-phone"/>:''}</td>
                                            <td>
                                                {this.getBtns(org)}
                                            </td>
                                        </tr>
                                    )
                                })
                            }
                        </Table>
                    </TabItem>
                    <TabItem>
                        <Form ref="orgForm">
                            <Item>
                                <Label>上级部门</Label>
                                <ButtonInput placeHolder="没有可以不填" ref="orgInput1" value={this.state.orgForm.parentOrg} onChange={(value)=>this.orgChange('parentOrg',value)}
                                             onClick={()=>{this.refs.orgModal.show({typeData:this.refs.orgInput1.inputRef})}} readonly="readonly">
                                </ButtonInput>
                                <TreeModal ref="orgModal" nodes={this.state.nodes} errorStr="还没有创建任何部门"
                                           onSelected={(string,data)=>{
                                               this.refs.orgInput1.value = string;
                                               this.state.orgForm.parentId = data.id;
                                           }}>
                                </TreeModal>
                            </Item>
                            <Item>
                                <Label>部门名称</Label>
                                <Input lay-verify="required" ref="orgName" value={this.state.orgForm.orgName} onChange={(value)=>this.orgChange('orgName',value)}/>
                            </Item>
                            <SecurityCheck roles="admin | secLevel">
                                <Item>
                                    <Label>负责人部门</Label>
                                    <LayuiCommSelect mask={['building', 'unit', 'floor', 'room']} firstValue="公司总部" value={this.state.currentComm}
                                                     commSelectShowStyle="ShowWhenOneComm" onChangeComm={(comm) => this.leaderCommOnChange(comm)}/>
                                </Item>
                            </SecurityCheck>
                            <Item>
                                <Label>选择负责人</Label>
                                <ButtonInput placeHolder="没有就直接输入" ref="leaderInput" onChange={(value)=>this.orgChange('staffName',value)} value={this.state.orgForm.staffName}
                                             onClick={()=>{this.refs.leaderModal.show({typeData:this.refs.leaderInput.inputRef})}} lay-verify="required">
                                </ButtonInput>
                                <Tips style={{marginLeft:5,marginTop:2}}>绑定部门负责人并不会开通APP权限,还需要手动去开通</Tips>
                                <TreeModal ref="leaderModal" nodes={this.state.leaderStaffNodes} errorStr="没有用户可选择"
                                           onSelected={(string,data)=>{this.leaderSelected(string,data)}}/>
                            </Item>
                            <Item>
                                <Label>电话</Label>
                                <Input lay-verify="number" ref="phoneNum" value={this.state.orgForm.phoneNum} onChange={(value)=>this.orgChange('phoneNum',value)}/>
                            </Item>
                            <Item>
                                <Label>邮箱</Label>
                                <Input ref="email" value={this.state.orgForm.email} onChange={(value)=>this.orgChange('email',value)}/>
                            </Item>
                            <Item>
                                <Button lay-submit="true" btnType="normal" formBtn="true" onClick={() => this.createOrg()}>确定</Button>
                            </Item>
                        </Form>
                    </TabItem>
                </Tab>
                <Modal title="员工创建" ref="staffModal" area={['420px']} endCallback={()=>{this.setState({staffForm:emptyObj(this.state.staffForm)})}}>
                    <Form size="sm">
                        <Item>
                            <Label>员工名称</Label>
                            <ButtonInput ref="staffName" lay-verify="required" value={this.state.staffForm.staffName} onChange={(value)=>this.staffChange('staffName',value)}
                                         onClick={()=>{this.refs.staffSelectTreeModal.show({typeData:this.refs.staffName.inputRef})}} size="sm"/>
                        </Item>
                        <SecurityCheck roles="admin | secLevel">
                            <Item>
                                <Label>部门类型</Label>
                                <LayuiCommSelect size="sm" mask={['building', 'unit', 'floor', 'room']}  firstValue="公司总部"
                                                 commSelectShowStyle="ShowWhenOneComm" commCode={this.state.staffForm.commCode} onChange={(value)=>this.staffCommOnChange(value)}/>
                            </Item>
                        </SecurityCheck>
                        <Item>
                            <Label>所属部门</Label>
                            <ButtonInput readonly="readonly" ref="orgInput" value={this.state.staffForm.orgName} lay-verify="required"
                                         onChange={(value)=>this.staffChange('orgName',value)}
                                         onClick={()=>{
                                             if(this.staffModify)
                                                this.refs.staffTreeModal.show({typeData:this.refs.orgInput.inputRef});
                                             else
                                                 layui.layer.msg("已经选择了部门，不能在此修改");
                                         }} size="sm" >
                            </ButtonInput>
                        </Item>
                        <Item>
                            <Label>员工类型</Label>
                            <Select ref="staffType" lay-verify="required" value={this.state.staffForm.staffType} onChange={(value)=>this.staffChange('staffType',value)}>
                                <option value="">请选择</option>
                                <option value="3">部门主管</option>
                                <option value="30">部门员工</option>
                            </Select>
                            <Tips>目前并不支持一个员工同时在多个部门拥有不同的职位</Tips>
                        </Item>
                        <Item>
                            <Label>电话</Label>
                            <Input ref="staffPhone" lay-verify="number" value={this.state.staffForm.phoneNum} onChange={(value)=>this.staffChange('phoneNum',value)}/>
                        </Item>
                        <Item>
                            <Label>邮箱</Label>
                            <Input ref="staffEmail" value={this.state.staffForm.email} onChange={(value)=>this.staffChange('email',value)}/>
                        </Item>
                        <Item>
                            <Label>APP权限</Label>
                            <Select style={{marginRight: 0}} value={this.state.staffForm.role}
                                    onChange={(value)=>{this.staffChange('role',value);this.setState({})}}
                            >
                                <option value="">不开启</option>
                                {
                                    this.state.roles.length > 0 ? this.state.roles.map((role) => {
                                        return <option value={role.id}>{role.name}</option>
                                    }) : ''
                                }
                            </Select>
                            <Button btnType="primary" size="sm" onClick={() => this.goToRolePage()}>添加角色&nbsp;
                                <Tips>{this.appAuthTips}</Tips>
                            </Button>
                        </Item>
                        <Item style={this.state.staffForm.role && !this.headQuarters?{}:{display:'none'}}>
                            <Label>管理机绑定</Label>
                            <Select value={this.state.staffForm.devBinding} onChange={(value)=>this.staffChange('devBinding',value)}>
                                <option value="">不绑定</option>
                                {this.getManagerDevOption()}
                            </Select>
                            <Tips>绑定管理机之后,业主呼叫管理处时,手机会同时收到呼叫</Tips>
                        </Item>
                        <Item>
                            <Button className="layui-btn layui-btn-normal layui-btn-sm layui-form-btn" lay-submit="true"
                                    onClick={() => this.addStaff()}>确定</Button>
                        </Item>
                    </Form>
                </Modal>
                <TreeModal ref="staffTreeModal" nodes={this.state.staffTreeOrgNodes} onSelected={
                    (string,data)=>{
                        this.refs.orgInput.value = string;
                        this.state.staffForm.orgId = data.id;
                    }
                }/>
                <TreeModal ref="staffSelectTreeModal" nodes={this.state.staffNodes} errorStr="没有用户可选择"
                           onSelected={(string,data)=>{this.staffSelect(string,data)}}/>
            </Frame>

        )
    }
}

ReactDOM.render(<QueryPropertyOrg/>, document.getElementById("queryPropertyOrg"));